package drds.plus.executor.transaction.non_transaction_and_close_connection_when_commit;


import drds.plus.datanode.api.Connection;
import drds.plus.datanode.api.DatasourceManager;
import drds.plus.executor.ExecuteContext;
import drds.plus.executor.transaction.AbstractTransaction;
import drds.plus.executor.transaction.strict_write_with_non_transaction_cross_database_read.ReadWrite;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;

/**
 * 提交时关闭连接
 */
@Slf4j
public class NonTransactionAndCloseConnectionWhenCommitTransaction extends AbstractTransaction {

    private drds.plus.executor.transaction.ConnectionHolder connectionHolder = null;

    public NonTransactionAndCloseConnectionWhenCommitTransaction(ExecuteContext executeContext) {
        super(executeContext);

        connectionHolder = new NonTransactionAndCloseConnectionWhenCommitConnectionHolder();
    }

    public Connection getConnection(@NonNull String dataNodeId, DatasourceManager datasourceManager, ReadWrite readWrite) throws SQLException {

        lock.lock();
        try {
            Connection connection = this.getConnectionHolder().getConnection(dataNodeId, datasourceManager);
            return connection;
        } finally {
            lock.unlock();
        }
    }

    public void commit() throws RuntimeException {

        close();

    }

    public void rollback() throws RuntimeException {

        throw new RuntimeException("ERR_ROLLBACK_AUTOCOMMIT_TRANSACTION");
    }

    public void tryClose(String dataNodeId, Connection connection) throws SQLException {
        lock.lock();

        try {
            this.getConnectionHolder().tryClose(dataNodeId, connection);
        } finally {
            lock.unlock();
        }
    }

    public drds.plus.executor.transaction.ConnectionHolder getConnectionHolder() {
        return this.connectionHolder;
    }

    public void close() {
        if (isClosed()) {
            return;
        }

        lock.lock();

        try {
            super.close();

            this.getConnectionHolder().closeConnectionSet();
        } finally {
            lock.unlock();
        }
    }

    public void tryClose() throws SQLException {
        this.close();

    }
}
